<?php

require_once('Adept/Db/IConnection.php');

final class Adept_Db_Factory 
{

    private $defaultConnection;
    private $connections;

    static private $instance;

    static public function getInstance()
    {
        if (!isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    static function setDefaultConnection($connection)
    {
        $instance = self::getInstance();
        $instance->defaultConnection = $connection;
    }

    private function createConnection($cs)
    {
        $config = new Adept_Db_Config($cs);
        $driver = $config->getDriver();
        $className = $config->getDriverClassName();

        Adept::loadClass($className);

        return new $className($config);
    }

    /**
     * Get connection interface object. Connect operation run automatically
     * 
     * <pre>
     * // Get default DB connection:
     * $db = DbFactory::getConnection();
     * // Get specific DB conenction:
     * $db = DbFactory::getConnection('MySql://user:root@localhost/testdb');
     * </pre>
     * 
     * @throws Adept_Db_Connection
     *
     * @param string $cs Connection string like Driver://user:password@host/dbname
     * @return Adept_Db_IConnection
     */
    static public function getConnection($cs = null)
    {
        $instance = self::getInstance();
        if (is_null($cs)) {
            $cs = $instance->defaultConnection;
            if ($instance->defaultConnection == null) {
                throw new Adept_Db_Exception('Default connection not defined');
            }
        }
        if (!isset($instance->connections[$cs])) {
            $instance->connections[$cs] = $instance->createConnection($cs);
            $instance->connections[$cs]->connect();
        }
        return $instance->connections[$cs];
    }

}